<template>
  <div class="container-full">
    <div class="toolbar">
      <div class="btn-group" role="group" aria-label="Basic example">
        <button type="button" class="btn" @click="close()">
          <i class="iconfont icon-shangyibu1"></i> 返回
        </button>
        <!-- <button type="button" class="btn" @click="addToCart()">
          <i class="iconfont icon-arrowright"></i> 加入所选
        </button>-->
      </div>
    </div>
    <form class="form-inline filter-pane" v-on:submit.prevent="onSearch()">
      <div class="form-group" style="padding-right:10px">
        <input type="text" class="form-control" placeholder="关键词" v-model="keyword">
      </div>
      <button type="button" class="btn btn-primary" @click="onSearch()">查询</button>
    </form>
    <div class="grid-host">
      <div class="grid" id="productGrid">
        <div class="grid-body">
          <table border="0" cellpadding="0" cellspacing="0">
            <thead>
              <tr class="grid-hidden-header">
                <th width="60px">图片</th>
                <th width="280px">商品名称</th>
                <th :key="col.name" v-for="col in columns" :width="col.width">{{col.text}}</th>
              </tr>
            </thead>
            <tbody>
              <tr :key="entry.id" v-for="entry in items">
                <td>
                  <img
                    :src="'https://data.ysmove.com/' + entry.default_image"
                    class="img-responsitive"
                    style="max-height:48px;max-width:48px"
                  >
                </td>
                <td style="position:relative;padding-right:36px">
                  <span>{{entry.goods_name}}</span>
                  <button
                    class="btn btn-sm btn-secondary-outline btn-cart"
                    @click="handlePickSpecEvent(entry)"
                  >
                    <i class="iconfont icon-plus"></i>
                  </button>
                </td>
                <td :key="col.name" v-for="col in columns" class="cell-content">
                  <a
                    v-if="col.cellClick"
                    href="javascript:;"
                    v-on:click="onItemClick(col, entry)"
                  >{{entry[col.name]}}</a>
                  <span v-else>{{entry[col.name]}}</span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="grid-footer">
          <div v-if="pageable != null" class="footer-content">
            <div class="status">共找到记录: {{pageable.totalCount}}</div>
            <div class="pager">
              <a
                v-if="pageable.currentPage > 1"
                href="javascript:;"
                v-on:click="goto(pageable.currentPage - 1)"
              >上一页</a>
              {{pageable.currentPage}} / {{pageable.pageCount}}
              <a
                v-if="pageable.currentPage < pageable.pageCount"
                href="javascript:;"
                v-on:click="goto(pageable.currentPage + 1)"
              >下一页</a>
            </div>
          </div>
        </div>
      </div>
      <div class="cart">
        <div class="cart-header">
          <a class="cart-toggler" @click="toggleCart()" href="javascript:;">
            <i class="iconfont icon-right"></i>
          </a>
          <span class="cart-title">购物车</span>
        </div>
        <div class="cart-body">
          <table>
            <thead>
              <tr>
                <th>商品</th>
                <th>单价</th>
                <th width="80px">数量</th>
              </tr>
            </thead>
            <tbody>
              <tr :key="item.id" v-for="item in cartItems" style="vertical-align:top">
                <td>{{item.name}}[{{item.spec_name}}]</td>
                <td>{{item.price}}</td>
                <td>
                  <input type="number" class="form-control" v-model="item.quantity">
                  <button class="btn btn-sm btn-cart-remove" @click="removeCartItem(item)">
                    <i class="iconfont icon-shanchu"></i>
                  </button>
                </td>
              </tr>
            </tbody>
            <tfoot>
              <tr>
                <td colspan="3" style="text-align:right">共 {{quantity}} 件, 合计: {{ totals }}</td>
              </tr>
              <tr v-if="cartItems.length > 0">
                <td colspan="3">
                  <button class="btn btn-primary" @click="showOrderDialog()">下单</button>
                  <button class="btn btn-primary" @click="clearCart()">清空</button>
                </td>
              </tr>
            </tfoot>
          </table>
        </div>
      </div>
    </div>
    <div id="order-dialog" class="modal" tabindex="-1" role="dialog">
      <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">下单</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <form role="form">
              <div class="form-group">
                <label class="control-label">买家</label>
                <input class="form-control" :value="customer.real_name" disabled="disabled">
              </div>
              <div class="form-group">
                <label class="control-label">电话</label>
                <input class="form-control" v-model="order.addr_phone_mob" disabled="disabled">
              </div>
              <div class="form-group">
                <label class="control-label">金额</label>
                <input class="form-control" :value="totals" disabled="disabled">
              </div>
              <div class="form-group">
                <label class="control-label">支付方式</label>
                <select class="form-control" v-model="order.payment_id">
                  <option
                    :key="item.payment_id"
                    v-for="item in payments"
                    :value="item.payment_id"
                  >{{item.payment_name}}</option>
                </select>
              </div>
              <div class="form-group">
                <label class="control-label">地址</label>
                <select class="form-control" v-model="order.addr_id">

                  <!-- <option
                    v-if="address"
                    :value="address.addr_id"
                    selected="selected"
                  >{{address.region_name + ' ' + address.address}}</option> -->
                  <option :key="index"
                    v-for="(item,index) in addressList"
                    :value="item.addr_id"
                  >{{item.region_name + ' ' + item.address}}</option>
                </select>
              </div>
              <div class="form-group">
                <label class="control-label">备注</label>
                <textarea class="form-control" v-model="order.postscript" rows="3"></textarea>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-primary" :disabled="order.addr_id == null || order.addr_id == undefined" v-on:click="submitOrder()">确定</button>
            <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
          </div>
        </div>
      </div>
    </div>
    <div id="spec-dialog" class="modal" tabindex="-1" role="dialog">
      <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">选择商品规格</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <table class="table">
              <thead>
                <tr>
                  <th>规格</th>
                  <th>单价</th>
                  <th>数量单位</th>
                  <th>库存</th>
                </tr>
              </thead>
              <tbody>
                <tr :key="item.spec_id" v-for="(item,index) in specifications">
                  <td>
                    <label class="custom-control custom-control-inline custom-radio">
                      <input
                        type="radio"
                        name="selectedSpec"
                        :value="index"
                        :checked="item.spec_id == defaultSpecId"
                        class="custom-control-input"
                        :id="'spec_radio_' + item.spec_id"
                      >
                      <label class="custom-control-label" :for="'spec_radio_' + item.spec_id">{{item.spec_1}}</label>
                    </label>
                  </td>
                  <td>{{item.price}}</td>
                  <td>{{item.single_counts}}</td>
                  <td>{{item.stock}}</td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-primary" v-on:click="handleAddToCartEvent()">确定</button>
            <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "CreateOrder",
  data() {
    return {
      order: {
        addr_id: ""
      },
      keyword: "",
      specifications: [],
      defaultSpecId: null,
      currentProduct: null,
      items: [],
      customerId: null,
      customer: {},
      address: null,
      addressList: [],
      cartItems: [],
      payments: [],
      pageable: null,
      columns: [
        { text: "品牌", name: "brand", width: "100px" },
        { text: "存量", name: "spec_qty", width: "60px" },
        { text: "单价", name: "price", width: "120px" }
      ]
    };
  },
  methods: {
    showOrderDialog() {
      this.order["goods_amount"] = this.calculateTotals();
      console.log(this.order.goods_amount);

      $("#order-dialog").modal("show");
    },
    submitOrder() {
      if (this.cartItems.length == 0) {
        alert("请选择商品");
        return;
      }

      var goods = [];
      for (var i = 0; i < this.cartItems.length; i++) {
        var item = this.cartItems[i];
        goods.push({
          goods_id: item.goods_id,
          price: item.price,
          spec_id: item.id,
          number: item.quantity,
          specification: item.spec_name
        });
      }

      const goodsJson = JSON.stringify(goods);
      var formData = {
        addr_id: this.order.addr_id,
        goodsJsonStr: goodsJson,
        payment_id: this.order.payment_id,
        postscript: this.order.postscript,
        buyer_id: this.customerId,
        addr_phone_mob: this.order.addr_phone_mob
      };

      if (!confirm("您确定要提交订单?")) return;
      
      $('#order-dialog').modal('hide');
      var self = this;
      this.$order.submit(formData).then(rsp => {
        var data = rsp.data;
        if (data.success) {
          alert("成功下单");

          //清空购物车
          while (self.cartItems.length > 0) {
            self.$delete(self.cartItems, 0);
          }

          //跳转到订单明细页面, 或者订单列表页
          self.$router.push({ path: "/order/index" });
        } else {
          console.log(rsp);
          alert(data.data.message);
        }
      });
    },
    handleAddToCartEvent() {
      var checkedItems = $('#spec-dialog input[name=selectedSpec]:checked');
      var len = checkedItems.length;
      if(len == 0) {
        alert('请选择一项规格');
        return;
      }

      var index = checkedItems.val();
      var selectedSpec = this.specifications[index];

      $('#spec-dialog').modal('hide');
      this.addToCart(this.currentProduct, selectedSpec);
    },
    handlePickSpecEvent(entry) {
      var self = this;
      this.$order.getProduct(entry.goods_id, this.customerId).then(rsp => {
        console.log(rsp);
        if (rsp.data.success) {
          self.currentProduct = rsp.data.data.goods;
          self.specifications = rsp.data.data.spec;
          self.defaultSpecId = rsp.data.data.goods.default_spec;
          $("#spec-dialog").modal("show");
        } else {
          console.log(rsp);
        }
      });
    },
    goto(page) {
      console.log("request page: ", page);
      const customerId = this.customerId;
      this.$order.getProducts(customerId, this.keyword, page).then(r => {
        const result = r.data;
        if (result.success) {
          this.items = result.data.items;
          this.pageable = result.data._meta;
        }
      });
    },
    getCheckControlId(entry) {
      var key = "0";
      if (entry) key = entry[this.keyName];
      return "chk_" + this.keyName + "_" + key;
    },
    close() {
      this.$router.push({ path: "/order/index" });
    },
    onSearch() {
      this.goto(1);
    },
    toggleCart() {
      $(".grid-host").toggleClass("cart-closed");
    },
    clearCart() {
      while (this.cartItems.length) {
        this.cartItems.pop();
        console.log("Cleared: ", this.cartItems.length);
      }
    },
    removeCartItem(item, $event) {
      var element = $(event.srcElement).closest("tr");

      var index = 0;
      for (var i = 0; i < this.cartItems.length; i++) {
        var cartItem = this.cartItems[i];
        if (cartItem.id == item.id) {
          index = i;
          break;
        }
      }

      if (index >= 0) {
        this.$delete(this.cartItems, index);
      }
    },
    addToCart(entry, spec) {
      var item = null;
      for (var i = 0; i < this.cartItems.length; i++) {
        var current = this.cartItems[i];
        if (current.id == spec.spec_id) {
          item = current;
          break;
        }
      }

      if (item == null) {
        item = {
          id: spec.spec_id,
          goods_id: entry.goods_id,
          name: entry.goods_name,
          spec_name: spec.spec_1,
          quantity: 1,
          price: spec.price,
          imageUrl: entry.default_image
        };

        this.cartItems.push(item);
      } else {
        item.quantity = item.quantity + 1;
      }
    },
    calculateTotals() {
      var sum = 0;
      for (var i = 0; i < this.cartItems.length; i++) {
        var item = this.cartItems[i];
        var q = parseInt(item.quantity);
        sum = sum + q * item.price;
      }

      return sum;
    }
  },
  created() {
    var query = this.$router.currentRoute.query;
    this.customerId = query.customerId;
    if (this.customerId) {
      var json = localStorage.getItem(this.customerId + "_cart");
      if (json != null) {
        this.cartItems = JSON.parse(json);
      }
    }
  },
  destroyed: function() {
    localStorage.removeItem(this.customerId + "_cart");

    if (this.cartItems.length > 0) {
      var json = JSON.stringify(this.cartItems);
      localStorage.setItem(this.customerId + "_cart", json);
    }
  },
  computed: {
    quantity: function() {
      var sum = 0;
      for (var i = 0; i < this.cartItems.length; i++) {
        var item = this.cartItems[i];
        sum = sum + parseInt(item.quantity);
      }

      return sum;
    },
    totals: function() {
      return this.calculateTotals();
    }
  },
  mounted() {
    $("#productGrid").grid();

    var json = localStorage.getItem("customer");
    if (json != null) {
      var customer = JSON.parse(json);
      if (customer.user_id != this.customerId) {
        this.$router.push({ path: "/order/index" });
        return;
      }

      this.customer = customer;
      this.order.addr_phone_mob = customer.phone_mob;
      //this.order.buyer_name = customer.real_name;
      this.order.real_buyer_id = customer.user_id;

      //获取商店信息
      var user = JSON.parse(localStorage.getItem("user"));
      var self = this;

      this.$user.getAddresses(this.customerId).then(rsp => {
        var data = rsp.data;
        console.log("fetch addressList:", data);
        if (data.success) {
          self.addressList = data.data.items;
          console.log("addr: ", data.data);
        } else {
          alert("获取地址信息失败");
        }
      });

      this.$user.getStoreInfo(user.user_id).then(rsp => {
        //console.log('store info: ', rsp);
        var data = rsp.data;
        if (data.success) {
          self.payments = data.data.payment;
        } else {
          alert("获取支付信息失败");
        }
      });

      this.goto(1);
    } else {
      this.$router.push({ path: "/order/index" });
    }
  }
};
</script>

<style lang="scss" scoped>
@import "@/assets/app.scss";

.container-full {
  display: block;
  position: relative;
  height: 100%;
  width: 100%;
  padding-top: 85px;
}

.filter-pane {
  position: absolute;
  top: 40px;
  padding: 15px;
}

.btn-cart-remove {
  color: red;
}

.grid-host {
  width: 100%;
  height: 100%;
  padding: 15px;
  position: relative;
  padding-right: 300px;
}

.grid-host.cart-closed {
  padding-right: 63px;
}

.grid-host.cart-closed .cart-toggler > i::before {
  content: "\e7ec";
}

.btn-cart {
  position: absolute;
  right: 4px;
  top: 10px;
  border: 1px solid rgb(0, 90, 158);
  visibility: hidden;
}

.btn-cart > i {
  color: rgb(0, 90, 158);
}

tr:hover .btn-cart,
.btn-cart:hover {
  visibility: visible;
}

.cart {
  position: absolute;
  right: 0px;
  width: 285px;
  bottom: 15px;
  top: 15px;
  // border: solid 1px rgb(234, 234, 234);
  // padding-left: 10px;
  // padding-right: 10px;
  background: white;
  -webkit-transition: width 0.4s; /* Safari */
  transition: width 0.4s;
  box-shadow: 0 0 0 1px rgba(20, 20, 31, 0.05),
    0 1px 3px 0 rgba(20, 20, 31, 0.15);
  padding-top: 40px;
}

.cart-body {
  width: 100%;
  height: 100%;
  padding-left: 10px;
  padding-right: 10px;
  position: relative;
  overflow: auto;
}

.cart-toggler {
  flex: 0;
  text-align: center;
  color: #a6abbd;
  text-decoration: none;
}

.cart-toggler:hover {
  color: rgb(0, 90, 158);
}

.cart-closed .cart {
  width: 48px;
}

.cart-closed .cart-title {
  writing-mode: tb-rl;
  text-align: left;
}

.cart-closed .cart table {
  display: none;
}

.cart-closed .cart-header {
  height: 100%;
  flex-direction: column;
}

.cart-header {
  width: 100%;
  display: flex;
  flex-direction: row;
  background-color: white;
  height: 38px;
  line-height: 38px;
  top: 0px;
  position: absolute;
  border-bottom: solid 1px $borderColor;
  padding-left: 10px;
  padding-right: 10px;
}

.cart-title {
  flex: 1;
  text-align: right;
  font-weight: 700;
}

.cart table {
  table-layout: fixed;
  width: 100%;
}

.cart table td,
.cart table th {
  padding: 6px;
}

.footer-content {
  display: flex;
  flex-direction: row;
  width: 100%;
  height: 100%;
}

.status {
  flex: 0 120px;
  height: 100%;
  vertical-align: middle;
  padding-left: 15px;
  line-height: 38px;
}

.pager {
  flex: 1;
  height: 100%;
  text-align: right;
  vertical-align: middle;
  padding-right: 15px;
  line-height: 38px;
}

.grid-footer {
  position: absolute;
  height: 38px;
  bottom: 0px;
  width: 100%;
  border-top: 1px solid $borderColor;
}
</style>

